import { Input } from 'antd'
import React, { useState, useRef,useEffect } from 'react'
import ReactQuill from 'react-quill'
import { showMessage } from '@/components/antd-comp/message'
import { CHAT_URL } from '@/components/Chat/constants'
import 'react-quill/dist/quill.snow.css'
import './style.css'
import { marked } from 'marked'
import Quill from 'quill'
const { TextArea } = Input
import MindMap from './mind'

// 在组件外部注册字体
const Font = Quill.import('formats/font')
Font.whitelist = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong']
Quill.register(Font, true)

// 添加自定义字体类
const fontAttributor = Quill.import('attributors/class/font')
fontAttributor.whitelist = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong']
Quill.register(fontAttributor, true)

const StreamEditor: React.FC = () => {
  const [content, setContent] = useState('')
  const [loading, setLoading] = useState(false)
  const quillRef = useRef<ReactQuill>(null)
  const esLinkSuccess = useRef(false)
  
  // 处理发送消息
  const handleSendClick = async (value: string) => {
    if (!value.trim() || loading) return
    
    setLoading(true)
    esLinkSuccess.current = false
    // 清空富文本编辑器内容
    setContent('')
    
    try {
      const response = await fetch(CHAT_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'text/event-stream'
        },
        body: JSON.stringify({
          messages: [
            {
              "role": "system",
              "content": [
                {
                  "type": "text",
                  "text": "111"
                }
              ]
            },
            {
              "role": "user",
              "content": [
                {
                  "type": "text",
                  "image_url": {
                    "url": "",
                    "detail": "auto"
                  },
                  "text": value
                }
              ],
              "createTime": 1743758526042
            }],
          stream: true,
          app_id: "70854a66-3d81-4477-961d-12b6b2a6d8e4",
          conversation_id: "90cc129c-e4b9-4ddd-ba4a-77abf350d0b1",
          disable_search: true,
          is_preview: 1,
          is_regenerate: false,
          sso_key: "test"
        })
      })

      if (!response.ok) {
        throw new Error(`请求失败，状态码: ${response.status}`)
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let buffer = ''
      let currentContent = ''
      let pendingText = ''
      let isFirstParagraph = true

      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value, { stream: true })
        buffer += chunk
        const lines = buffer.split('\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          if (line.startsWith('data: {')) {
            try {
              const jsonData = JSON.parse(line.slice(6))
              const text = jsonData.choices?.reduce((acc, choice) => acc + (choice.delta?.content || ''), '')
              
              if (text) {
                pendingText += text
                // 当遇到段落结束（两个换行符）或句号时处理文本
                if (pendingText.includes('\n\n') || pendingText.endsWith('。')) {
                  // 处理段落
                  let html = marked(pendingText)
                  // 为第一个段落添加额外的换行
                  if (isFirstParagraph) {
                    currentContent += html + '<br/><br/>'
                    isFirstParagraph = false
                  } else {
                    currentContent += html
                  }
                  setContent(currentContent)
                  pendingText = ''
                  
                  // 将光标移动到最后
                  const quill = quillRef.current?.getEditor()
                  if (quill) {
                    quill.setSelection(quill.getLength(), 0)
                  }
                }
              }
            } catch (e) {
              console.error('解析响应数据失败:', e)
            }
          }
        }
      }
      
      // 处理最后剩余的文本
      if (pendingText) {
        const html = marked(pendingText)
        currentContent += html
        setContent(currentContent)
      }

    } catch (error) {
      console.error('发送消息失败:', error)
      showMessage({
        content: '发送消息失败，请重试',
        type: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex h-screen w-full gap-4 bg-gray-100 p-4">
      {/* 左侧对话输入区 */}
      <div className="flex w-1/2 flex-col gap-4">
        <TextArea
          className="h-[200px] resize-none"
          placeholder="请输入对话内容..."
          onPressEnter={(e: React.KeyboardEvent) => {
            if (!e.shiftKey) {
              e.preventDefault()
              const value = (e.target as HTMLTextAreaElement).value
              handleSendClick(value)
              ;(e.target as HTMLTextAreaElement).value = ''
            }
          }}
        />
        <div className="text-sm text-gray-500">
          提示: 按 Enter 发送，Shift + Enter 换行
        </div>
      </div>

      {/* 右侧富文本编辑器 */}
      <div className="w-1/2">
        <ReactQuill
          ref={quillRef}
          theme="snow"
          value={content}
          onChange={setContent}
          readOnly={loading}
          modules={{
            toolbar: [
              [{ 'header': [1, 2, 3, false] }],
              [{ 'font': ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong'] }],  // 添加字体选项
              ['bold', 'italic', 'underline', 'strike'],
              [{ 'list': 'ordered'}, { 'list': 'bullet' }],
              ['link', 'image'],
              ['clean']
            ]
          }}
          formats={[
            'header',
            'font',
            'bold', 'italic', 'underline', 'strike',
            'list', 'bullet',
            'link', 'image'
          ]}
        />
      </div>

      {/* Loading 指示器 */}
      {loading && (
        <div className="fixed left-1/2 top-4 -translate-x-1/2 rounded bg-black/75 px-4 py-2 text-white">
          正在生成...
        </div>
      )}
      {MindMap()}
    </div>
  )
}

export default StreamEditor